<template>
   <el-row>
    <el-page-header @back="goBack" title="返回"  style=" margin-left:10px;margin-top:10px; color:cornflowerblue;"></el-page-header>
    <el-divider content-position="left"></el-divider>
        <el-form :model="addSpu" ref="addSpuForm">
            <el-form-item label="标题" label-width="70px" prop="title">
                <el-input v-model="addSpu.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="副标题" label-width="70px" prop="subtitle">
                <el-input v-model="addSpu.subtitle" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="价格" label-width="70px" prop="price">
                <el-input v-model="addSpu.price" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="折扣价" label-width="70px" prop="discountPrice">
                <el-input v-model="addSpu.discountPrice" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="分类" label-width="70px" prop="categoryId">
                <el-select v-model="addSpu.categoryId"  placeholder="请选择">
                 <el-option
                v-for="item in categorys"               
                :label="item.name"
                :key="item.id"
                :value="item.id">
                </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="是否上架" label-width="70px" prop="online">
            <el-switch v-model="addSpu.online"></el-switch>
            </el-form-item>

            <el-form-item label="主图" label-width="70px" prop="mainImgUrl">
                <el-upload
                    class="avatar-uploader"
                    action=""
                    :show-file-list="false"
                    :http-request="uploadFile"
                    :on-success="handleMainImgSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="this.addSpu.mainImgUrl" :src="this.addSpu.mainImgUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>

            <el-form-item label="轮播图" label-width="70px" prop="carouselImageUrls">
              <el-upload
                action=""
                class="avatar-uploader"
                :http-request="uploadFile"
                list-type="picture-card"
                :file-list="fileList"
                :on-success="handlePictureCardPreview"
                :on-remove="handleRemove"
                :limit='4'>
                <i class="el-icon-plus"></i>
              </el-upload>

              <el-dialog :visible.sync="dialogVisible">             
                    <!-- <img width="100%" :src="this.addSpu.carouselImages" alt="" />    -->
                    <img  width="100%" :src="this.addSpu.carouselImages"/>                     
              </el-dialog>
            </el-form-item>

            <el-form-item label="标签" label-width="70px" prop="dynamicTags">
            <el-tag
                :key="tag"
                v-for="tag in this.addSpu.dynamicTags"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)">
                {{tag}}
            </el-tag>
            <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm">
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">新增标签</el-button>
            </el-form-item>

            <el-form-item label="规格" label-width="70px" prop="specKeysIds">
                <el-select v-model="addSpu.specKeysIds" multiple placeholder="请选择" >
                 <el-option
                v-for="item in specKeys"               
                :label="item.id+'#'+item.name"
                :key="item.id"
                :value="item.id">
                </el-option>
                </el-select>
            </el-form-item>
            
            <el-form-item label="描述" label-width="70px" prop="description">
                <el-input v-model="addSpu.description" autocomplete="off"></el-input>
            </el-form-item>
            <el-button @click="closeAndReset">重 置</el-button>
            <el-button type="primary" @click="sureAdd">添 加</el-button>
        </el-form>
  </el-row>
</template>

<script>
import  VueCookies  from 'vue-cookies'
import http from '@/utils/request.js'
    const OSS = require('ali-oss')
    const client= new OSS({
      accessKeyId: 'LTAI5tBRSqJDJyEqimryPDzH',  // 阿里云KEY
      accessKeySecret: 'wP3KENQ5jPYlwSf0vKooIiFmOH9vT4', // 阿里云KEYSECRET
      bucket: 'll0803', // OSS bucket 名称 
      region: 'oss-cn-hangzhou', // bucket 地址
    })
export default {
    data() {
        return {
            dialogVisible: false,
            addSpu: {
                carouselImages: [],
                title:'',
                subtitle:'',
                price:'',
                discountPrice:'',
                categoryId:null,
                online:true,
                //主图属性
                mainImgUrl: '',              
                dynamicTags: [],
                specKeysIds:[],
                description:''
            },
            categorys:[],
            specKeys:[],
            fileList:[],
            //标签属性           
            inputVisible: false,
            inputValue: ''
        }
    },
    created(){
        this.current = this.$route.query.current
       
    },
    mounted(){
        this.defaultCategory()
        http.get('spec-key').then(res => {
          this.specKeys = res
        })
     },  

    methods: {
        // 确认添加
        async sureAdd() {
            try {
                // 通过await的方式校验表单的时候，如果校验不通过，this.$refs.editForm.validate()
                // 会抛出异常
                await this.$refs.addSpuForm.validate()
                // console.log(this.addSpu.carouselImages);
                // console.log(this.addSpu.dynamicTags);
                await http.post('spu',this.addSpu)
                this.fileList = [] 
                this.$message({ message: '添加成功', type: 'success', duration: 1000})
                this.defaultCategory()
                // 重置表单
                this.$refs.addSpuForm.resetFields()
                this.goBack()
            }catch(err) {
                console.log(err);
            }
        },
        // 关闭并重置
        closeAndReset() {
            this.defaultCategory()
            this.fileList = []     
            // 重置表单
            this.$refs.addSpuForm.resetFields()        
        },
        //默认选中分类
      defaultCategory(){
        http.get('subCategory/getAll').then(res => {
          this.categorys = res
          this.addSpu.categoryId = this.categorys[0].id
        })
      },
        //标签方法 删除
      handleClose(tag) {
        this.addSpu.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      },
      
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
       },
       //标签方法 添加
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
            this.addSpu.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
        console.log(this.addSpu.dynamicTags);
      },
      //主图方法
      handleMainImgSuccess(res) {
        this.addSpu.mainImgUrl = res.url
        // console.log(this.addSpu.mainImgUrl);
      },
      beforeAvatarUpload(file) {
        const isJPEG = file.type === 'image/jpeg'
        const isJPG = file.type === 'image/jpg'
        const isPNG = file.type === 'image/png'
        const imgFormat = !isJPG && !isJPEG && !isPNG
        const isLt4M = file.size / 1024 / 1024 < 4 
        if (imgFormat) {
          this.$message.error('上传头像图片只能是JPG或者PNG格式!');
        }
        if (!isLt4M) {
          this.$message.error('上传头像图片大小不能超过 4MB!');
        }
        return !imgFormat && isLt4M
      },
    async uploadFile (options) {
    try {
        let file = options.file; // 拿到 file
        let fileName = file.name.substr(0,file.name.lastIndexOf('.'))
        let date = new Date().getTime()
        let fileNames = `${date}_${fileName}` // 拼接文件名，保证唯一，这里使用时间戳+原文件名
              // 上传文件,这里是上传到OSS的 uploads文件夹下
        client.put('SPU/' + fileNames, file).then(res=>{
        if (res.res.statusCode === 200) {
        options.onSuccess(res)
        }else {
            options.onError("上传失败")
        }
      })
        }catch (e) {
         options.onError("上传失败")
        }
      },
      //轮播图方法 移除方法
      handleRemove(file) {
        console.log(file.url);
        this.addSpu.carouselImages.pop(file.url);
        this.fileList.pop(file);
        console.log(this.fileList);

        console.log(this.addSpu.carouselImages);
      },
      handlePictureCardPreview(file) {
        // console.log(file.url);
        this.addSpu.carouselImages.push(file.url);
        this.fileList.push({url:file.url})
        console.log(this.fileList);
        this.dialogVisible = false;
        console.log( this.addSpu.carouselImages);
    },
    goBack(){
        this.$router.push({
        path: './spu-list',
        query: {current:this.current}
        })
    },
    }
}
</script>

<style lang="scss" scoped>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-right: 10px;
    vertical-align: bottom;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>